<?php
/**
 * Html Validation and cleanup plugin.
 * 
 * @TODO: Tidy should be a configurable application resource.
 * @uses Zend_Controller_Plugin_Abstract
 */
class Core_Controller_Plugin_Tidy extends Zend_Controller_Plugin_Abstract {

	/**
	 * Explicitly enable tidy. It's on by default.
	 */
	public static function enable()
	{
		self::$enabled = true;
	}
	
	/**
	 * Explicitly disable tidy. It's on by default.
	 */
	public static function disable()
	{
		self::$enabled = false;
	}
	
	/**
	 * Flip this switch to disable.
	 * 
	 * @var boolean
	 */
	private static $enabled = true;
	
	/**
	 * Tidy configuration.
	 * 
	 * @var array
	 */
	protected static $_tidyConfig = array('indent' => false,
		'indent-attributes' => false,
		'indent-spaces' => 4,
		'sort-attributes' => 'alpha',
		'output-xhtml' => true,
		'drop-proprietary-attributes' => true,
		'drop-empty-paras' => true,
		'merge-divs' => false,
		'drop-font-tags' => true,
		'tab-size' => 4,
		'hide-comments' => true,
		'wrap' => 120
	);
	
	/**
	 * Tidy encoding.
	 * 
	 * @var string
	 */
	protected static $_tidyEncoding = 'UTF8';
	
	/**
	 * @var tidy|null
	 */
	protected $_tidy;

	/**
	 * Constructor: initialize cache
	 *
	 * @param  array|Zend_Config $options
	 * @return void
	 * @throws Exception
	 */
	public function __construct() {
	}

	/**
	 * Helper function- creates tidy instance.
	 * 
	 * @param string $string
	 */
	protected function getTidy($string = null) {
		if (null === $this->_tidy) {
			if (null === $string) {
				$this->_tidy = new tidy();
			} else {
				$this->_tidy = tidy_parse_string($string, self::$_tidyConfig, self::$_tidyEncoding);
			}
		}
		return $this->_tidy;
	}

	/**
	 * Tidy up our HTML
	 *
	 * @return void
	 */
	public function dispatchLoopShutdown() {
		if ( self::$enabled )
		{
			$response = $this->getResponse();
			$tidy = $this->getTidy($response->getBody());
			$tidy->cleanRepair();
			$response->setBody((string) $tidy);
		}
	}
}
